package com.techstar.ats.netty.handler;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.time.LocalDate;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import com.techstar.ats.FtpProperties;
import com.techstar.ats.MessageType;
import com.techstar.ats.ScheduleMode;
import com.techstar.ats.dxp.AtsMessage;
import com.techstar.ats.dxp.history.rep.AbstractSchedule;
import com.techstar.ats.dxp.history.rep.F22InusedSchedule;
import com.techstar.ats.dxp.history.rep.F23HistorySchedule;
import com.techstar.ats.utils.FtpHelper;

public class ScheduleHandler extends ChannelInboundHandlerAdapter {
	private final FtpProperties ftpProperties;

	public ScheduleHandler(FtpProperties ftpProperties) {
		this.ftpProperties = ftpProperties;
	}

	private void schedule(AbstractSchedule as, ScheduleMode mode, LocalDate date) throws IOException {
		String filePath = FtpHelper.getLocalFile(date, as.line, mode);
		File file = new File(filePath);
		switch(as.sub) {
			case START:
				if(file.exists()) {
					file.delete();
				}
				break;
			case DATA:
				try(FileOutputStream os = new FileOutputStream(filePath, true);
				    OutputStreamWriter writer = new OutputStreamWriter(os, FtpHelper.GBK)) {
					writer.write(as.toCsvString());
				}
				break;
			case END:
				FtpHelper.ftpUp(this.ftpProperties, date, filePath);
		}
	}

	private void inusedSchedule(F22InusedSchedule is) throws IOException {
		LocalDate date = is.datetime.toLocalDate();
		schedule(is, ScheduleMode.INUSED, date.minusDays(1));
	}

	private void historySchedule(F23HistorySchedule hs) throws IOException {
		schedule(hs, ScheduleMode.HISTORY, hs.datetime.toLocalDate());
	}

	public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
		try {
			if(msg instanceof AtsMessage) {
				int msgId = ((AtsMessage) msg).id;
				MessageType messageType = MessageType.valueOf(msgId);
				switch(messageType) {
					case INUSED_SCHEDULE:
						this.inusedSchedule((F22InusedSchedule) msg);
						break;
					case HISTORY_SCHEDULE:
						this.historySchedule((F23HistorySchedule) msg);
				}
			}
		} finally {
			super.channelRead(ctx, msg);
		}
	}
}
